package com.example.sender;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.example.bean.UDPSendPackage;
import com.example.terminal.TerminalClient;
import com.example.type.StreamType;

public class UDPSender {
	private final static Logger log = LoggerFactory.getLogger(UDPSender.class);
	private final static Logger plog = LoggerFactory.getLogger("PackageThread");
	
	private DatagramSocket v_sendsocket; 				// 视频
	private DatagramSocket r_sendsocket; 				// 音频
	private long framenum = 0;							
	private byte framedatasend[] = new byte[548];		// 视频帧byte
	private int packbodysize = 519;						// 视频数据长度
	private int packheadersize = 29;					// 视频头长度
//	private MainActivity mainActivity1;					// MainActivity
	private byte[] audioframe = new byte[200];			// 语音buffer
	private String rip = ""; 							// 接收端ip
	private int v_port = 0; 							// 接收端视频端口
	private int r_port = 0; 							// 接收端视音频端口
	private boolean isstop = false;						// 是否通知activity停止发送视频

	public UDPSender(String ip, int vport, int rport, DatagramSocket v_sendsocket, DatagramSocket r_sendsocket) {
		this.isstop = false;
		this.rip = ip;
		this.v_port = vport;
		this.r_port = rport;
		this.v_sendsocket = v_sendsocket;
		this.r_sendsocket = r_sendsocket;
	}
	
//	public void sendStream(final byte[] frame, StreamType type) throws Exception {
//		DatagramPacket pack = new DatagramPacket(framedatasend, frame.length, InetAddress.getByName(rip), v_port);
//		if(StreamType.Audio == type){
//			r_sendsocket.send(pack);
//		}else if(StreamType.Vedio == type){
//			v_sendsocket.send(pack);
//		}
//	}
	
	public void sendStream(File file, StreamType type) throws Exception {
		sendStream(file, type, null);
	}
	
	public void sendStream(File file, StreamType type, TerminalClient client) throws Exception {
		DatagramSocket socket = null;
		if(StreamType.Audio == type){
			socket = r_sendsocket;
		}else if(StreamType.Vedio == type){
			socket = v_sendsocket;
		}
		
		InputStream input = new FileInputStream(file);
		int packageSize = 548;
		byte[] buffer = new byte[packageSize];
		
//		int size = input.available();
//		byte[] buffer = FileUtils.readFileToByteArray(file);
		int len = -1;

//		UDPSendPackage udpPack = new UDPSendPackage();
		
		DatagramPacket pack = null;
		while(true){
			len = input.read(buffer);
			
			pack = new DatagramPacket(buffer, len, InetAddress.getByName(rip), v_port);
			log.debug("start to send {} stream to {}:{}, size {}", type, rip, v_port, buffer.length);
			socket.send(pack);
			
			if(client != null){
				client.sendPackages++;
			}
			
			if(input.available() <= 0){
				break;
			}
		}
		
		input.close();
		socket.close();
	}

	public int sendVedio(int tid, int total, int no) throws Exception {
		DatagramSocket socket = null;
		socket = v_sendsocket;
		
		int packageSize = 274;
		byte[] buffer = new byte[packageSize];
		
		for(int i = 0; i < packageSize; i++){
			buffer[i] = 'a';
		}
		
		DatagramPacket pack = null;
		int count = 0;
		while(total == 0 || count < total){
			pack = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(rip), v_port);
			socket.send(pack);
			count++;
			
//			System.out.println("terminal[" + tid + "] send package count " + count);
			plog.info("terminal[{}] send package count {}", no, count);
//			log.debug("start to send vedio stream to {}:{}, size {}", rip, v_port, buffer.length);
			
			Thread.sleep(100);
		}
		
		return count;
	}
	
/*	
	// 将视频解码的数据发送出去，要循环所有的已经连接的客户端发送出去，暂时不用线程，因为这个会在别的线程里面被调用。
	public void sendFrame(final byte[] frame, int type) {
		DatagramPacket pack;
		try {
			if (type == 1) // 视频
			{
				framenum++;
				log.info("datagramsend len: {}", frame.length);
				// 分包循环发送,包号从1开始 packnum从1开始
				int packtotal = frame.length / packbodysize;
				if (packtotal * packbodysize < frame.length)
					packtotal++; // 尾部留了个余数。。。
				for (int packetnum = 1; packetnum <= packtotal; packetnum++) {
					framedatasend[0] = 1;												// 1表明是视频
					LongUtil.long2Byte(framedatasend, 1, framenum); 					// 9个过去了，帧号
					LongUtil.intToByteArray1(framedatasend, 9, packtotal); 				// 13个过去了 包数
					LongUtil.intToByteArray1(framedatasend, 13, packetnum); 			// 17个过去了 包号
					LongUtil.intToByteArray1(framedatasend, 17, frame.length); 			// 21个过去了，帧长度
					LongUtil.long2Byte(framedatasend, 21, System.currentTimeMillis());	//时间戳	8位

					// 时间戳
					int remaincount = 0;
					if (packetnum == packtotal) // 最后一个包
					{
						remaincount = frame.length - (packetnum - 1)
								* packbodysize;
					} else {
						remaincount = packbodysize;
					}
					System.arraycopy(frame, (packetnum - 1) * (packbodysize),
							framedatasend, 29, remaincount);
					pack = new DatagramPacket(framedatasend, remaincount
							+ packheadersize, InetAddress.getByName(rip),
							v_port);
					v_sendsocket.send(pack);
				}
			}
			if (type == 2) // 音频，这里包已经足够小了，不需要在拆包了
			{
				audioframe[0] = 2;// 2表明是音频
				System.arraycopy(frame, 0, audioframe, 1, frame.length);
				pack = new DatagramPacket(audioframe, frame.length + 1,
						InetAddress.getByName(rip), r_port);
				r_sendsocket.send(pack);
			}
		} catch (SocketException e1) {
			e1.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
//		if(mainActivity1.getLasttime()>0){
//			Log.e("action", "间隔时间："+(System.currentTimeMillis() - mainActivity1.getLasttime()) );
//			if((System.currentTimeMillis() - mainActivity1.getLasttime())>10000){
//				if(!isstop){
//					isstop = true;
//					mainActivity1.deinit();
//					Log.e("action", "T停止播放第一步" );					
//				}
//			}
//		}
	}
*/	
	public void setIsstop(boolean isstop) {
		this.isstop = isstop;
	}
}
